package controllers

import (
	"fmt"
	"github.com/gin-gonic/gin"
	bizcode "mall-api-gin/pkg/bizerror"
	"mall-api-gin/pkg/e"
	"mall-api-gin/pkg/util"
	"mall-api-gin/service"
	valid "mall-api-gin/validation"
	"net/http"
)

type PasswordController struct {
	BaseController
}

// Login 登录，未做安装校验（手机号码的校验），手机号码不存在的没做注册操作
func (con PasswordController) Login(ctx *gin.Context) {
	defer con.PanicHandler(http.StatusOK)
	con.C = ctx
	// 参数校验
	postData := new(valid.LoginValidate)
	con.ParseJson(ctx, &postData)
	errMsg := postData.Valid()
	if errMsg != nil {
		con.ErrResponse(http.StatusBadRequest, e.InvalidParams, errMsg.Error())
	}
	user, err := service.UserService.GetByMobile(postData.Mobile)
	if err != nil {
		con.ErrResponse(http.StatusOK, e.ErrorDb, err)
	}
	fmt.Printf("用户信息：mobile：%v user_id：%d\n", user.Mobile, user.ID)
	token, err := util.GenerateToken(user.Mobile, user.ID)
	fmt.Printf("错误：%v\n", err)
	if err != nil {
		con.ErrResponse(http.StatusOK, e.ERROR, err)
	}
	con.Response(http.StatusOK, bizcode.SUCCESS, gin.H{
		"userInfo": user,
		"token":    token,
	})
}

// ParseToken 解析token
func (con PasswordController) ParseToken(ctx *gin.Context) {
	defer con.PanicHandler(http.StatusOK)
	con.C = ctx
	token := ctx.Request.Header.Get("token")
	result, err := util.ParseToken(token)
	if err != nil {
		con.ErrResponse(http.StatusOK, e.ERROR, err)
	}
	fmt.Println(result)
	con.Response(http.StatusOK, bizcode.SUCCESS, result)
}

// Captcha 生成图形验证码
func (con PasswordController) Captcha(ctx *gin.Context) {
	defer con.PanicHandler(http.StatusOK)
	con.C = ctx
	id, content, err := util.Generate()
	if err != nil {
		con.ErrResponse(http.StatusOK, e.ERROR, err)
	}
	con.Response(http.StatusOK, bizcode.SUCCESS, gin.H{
		"captchaId": id,
		"content":   content,
	})
}

// Verify 生成图形验证码
func (con PasswordController) Verify(ctx *gin.Context) {
	defer con.PanicHandler(http.StatusOK)
	con.C = ctx
	id := ctx.DefaultQuery("captchaId", "")
	captchaVal := ctx.DefaultQuery("captchaVal", "")
	if !util.Verify(id, captchaVal) {
		con.ErrResponse(http.StatusOK, e.ERROR, "验证码错误")
	}
	con.Response(http.StatusOK, bizcode.SUCCESS, nil)
}
